import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'

// const UserContext = createContext()

const UserContextState = createContext() // 读取 state
const UserContextUpdater = createContext() // 改变 state

const useUserContextState = () => {
  const context = useContext(UserContextState)
  if (context === undefined) {
    throw new Error('useUserContextState 必须在它自己的Provider里使用')
  }
  return context
}

const useUserContextUpdater = () => {
  const context = useContext(UserContextUpdater)
  if (context === undefined) {
    throw new Error('useUserContextUpdater 必须在它自己的Provider里使用')
  }
  return context
}

const UserContextProvider = ({ children }) => {
  const [user, setUser] = useState(null)

  const signout = useCallback(() => {
    setUser(null)
  }, [])

  useEffect(() => {
    const controller = new AbortController()
    fetch('https://randomuser.me/api/', {
      signal: controller.signal,
    })
      .then((resp) => resp.json())
      .then((json) => new Promise((resolve) => setTimeout(() => resolve(json), 3000)))
      .then((json) => setUser(json.results[0]))
      .catch((error) => console.log('错误：', error))
    return () => {
      controller.abort()
    }
  }, [])

  // const contextValue = useMemo(() => ({user, signout})
  //   , [user, signout])

  return (
    <UserContextState.Provider value={user}>
      <UserContextUpdater.Provider value={signout}>{children}</UserContextUpdater.Provider>
    </UserContextState.Provider>
  )
}

// const useUserContext = () => {
//   const context = useContext(UserContext)
//   if (context === undefined) {
//     throw new Error(
//       'useUserContext必须在<UserContextProvider>内部使用'
//     )
//   }
//   return context
// }

export { UserContextProvider, useUserContextState, useUserContextUpdater }
